#!/bin/bash

install_mode=$1
download_url=https://ghproxy.com/https://github.com/fatedier/frp/releases/download/v0.48.0/frp_0.48.0_linux_amd64.tar.gz
BASE_DIR=$(cd $(dirname $0);pwd)
package_name=${download_url##*/}
frp_dir=${BASE_DIR}/${package_name%%.tar.gz}

FRP_HOME=/usr/local/$1
echo "FRP_HOME=${FRP_HOME}"

[[ ! -e "${package_name}" ]] && curl -O# "${download_url}"
tar -zxf "${package_name}"

if [[ "${install_mode}" == "frps" ]];then
    frps_path=${FRP_HOME}/frps
    frps_config_path=${FRP_HOME}/frps.ini
	[[ ! -e "${FRP_HOME}"  ]] && mkdir -p "${FRP_HOME}"
    \cp -r ${frp_dir}/frps* ${FRP_HOME}
    cat > ${frps_config_path} << EOF
[common]
bind_port = 57000
log_file=${FRP_HOME}/frps.log
log_level=debug
log_max_days=3
authentication_method=token
token = daweibalang@1024
vhost_http_port = 50080
vhost_https_port = 50443
subdomain_host = daweibalang.com
dashboard_port = 57500
dashboard_user = admin
dashboard_pwd = daweibalang@1024
EOF

    cat > /etc/systemd/system/frps.service <<EOF
[Unit]
Description = frps server
After = network.target syslog.target
Wants = network.target

[Service]
Type = simple
ExecStart = ${frps_path} -c ${frps_config_path}

[Install]
WantedBy = multi-user.target
EOF
elif [[ "${install_mode}" == "frpc" ]];then
    frpc_path=${FRP_HOME}/frpc
    frpc_config_path=${FRP_HOME}/frpc.ini
	[[ ! -e "${FRP_HOME}"  ]] && mkdir -p "${FRP_HOME}"
    \cp -r ${frp_dir}/frpc* ${FRP_HOME}
	cat > ${frpc_config_path} << EOF
[common]
server_addr = daweibalang.com
server_port = 57000
token = daweibalang@1024
log_file=${FRP_HOME}/frpc.log
log_max_days=3
admin_addr = 127.0.0.1
admin_port = 7400

[pve_https]
type = https
local_port = 8006
use_encryption = true
use_compression = true
subdomain = pve
locations = /
EOF

    cat > /etc/systemd/system/frpc.service <<EOF
[Unit]
Description = frpc server
After = network.target syslog.target
Wants = network.target

[Service]
Type = simple
ExecStart = ${frpc_path} -c ${frpc_config_path}

[Install]
WantedBy = multi-user.target
EOF
fi